package com.lz.ub.hm.impl

import com.lz.ub.hm.INVALID
import com.lz.ub.hm.UBLinkManager

/**
 * @author you
 * HM link管理器
 */
class HMLinkManager : UBLinkManager {

    //00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000
    //可以代表64（0~64）的唯一值
    private var links = 0L

    companion object {
        const val MAX_LINK = 32
    }

    //000111

    override fun remove(link: Int): Boolean {
        if (link in 1..MAX_LINK) {
            val index = link - 1
            if (links.shr(index).and(1).toInt() == 1) {
                links -= 1.shl(index)
            }
        }
        return false
    }

    override fun get(): Int {
        for (i in 0 until MAX_LINK) {
            val link = links.shr(i).and(1).toInt()
            if (link == 0) {
                links += 1.shl(i)
                return i + 1
            }
        }
        return INVALID
    }

    override fun reset() {
        links = 0L
    }
}